package net.zisen.cloud.core.security.handle;

import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tim/278002989@qq.com
 * @Classname ShiroExceptionHandle
 * @Description TODO
 * @Date 2019-04-01 23:10
 */
public class ShiroExceptionHandler implements HandlerExceptionResolver {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        Map<String, Object> model = new HashMap<String, Object>();
        if (e instanceof ShiroException || e instanceof UnauthorizedException) {
            logger.debug("访问未授权资源");
            request.getSession(true).setAttribute("REDIRECT_URL", request.getRequestURL() + "?" + request.getQueryString());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                response.sendError(401, "Need authentication!!!");
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            return new ModelAndView("redirect:/login", model);

        }
        return new ModelAndView("redirect:/error", model);
    }
}
